package com.hyk.commonLib.common.adapter;

import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.RecyclerView;

import com.hyk.commonLib.common.utils.ScreenUtils;

import java.lang.ref.SoftReference;

public class BaseViewHolder<DATA, DATA_BINDING extends ViewDataBinding> extends RecyclerView.ViewHolder {
    protected DATA_BINDING dataBinding;
    protected SoftReference<IAdapter<DATA>> adapterReference;

    public BaseViewHolder(@NonNull View itemView, IAdapter<DATA> adapter) {
        super(itemView);
        this.adapterReference = new SoftReference<>(adapter);
        if (useBinding()) dataBinding = DataBindingUtil.bind(itemView);

        if (bindOnClickListener() && !itemView.hasOnClickListeners()) {
            itemView.setOnClickListener(v -> notifyItemClickEvent());
        }
    }

    protected boolean positionValid() {
        return getBindingAdapterPosition() != RecyclerView.NO_POSITION;
    }

    protected IAdapter<DATA> getAdapter() {
        return adapterReference.get();
    }

    public void notifyItemClickEvent() {
        IAdapter<DATA> adapter = getAdapter();
        if (positionValid() && adapter != null) {
            adapter.notifyItemClickEvent(getBindingAdapterPosition());
        }
    }

    public void setMarginTopInDp(float margin) {
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) itemView.getLayoutParams();
        params.topMargin = ScreenUtils.dp2px(margin);
    }

    public void setMarginBottomInDp(float margin) {
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) itemView.getLayoutParams();
        params.bottomMargin = ScreenUtils.dp2px(margin);
    }

    protected boolean bindOnClickListener() {
        return false;
    }

    protected boolean useBinding() {
        return true;
    }

    public boolean canGetValidData() {
        return positionValid() && getAdapter() != null;
    }

    public DATA getData() {
        return ((IAdapter<DATA>) getAdapter()).getItem(getBindingAdapterPosition());
    }

    public DATA_BINDING getDataBinding() {
        return dataBinding;
    }
}
